/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.landery.modules.sinco.service.impl;

import me.landery.modules.sinco.domain.Customize;
import me.landery.modules.sinco.domain.em.CustomizeStatus;
import me.landery.utils.ValidationUtil;
import me.landery.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.landery.modules.sinco.repository.CustomizeRepository;
import me.landery.modules.sinco.service.CustomizeService;
import me.landery.modules.sinco.service.dto.CustomizeDto;
import me.landery.modules.sinco.service.dto.CustomizeQueryCriteria;
import me.landery.modules.sinco.service.mapstruct.CustomizeMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.landery.utils.PageUtil;
import me.landery.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author landery
* @date 2022-06-27
**/
@Service
@RequiredArgsConstructor
public class CustomizeServiceImpl implements CustomizeService {

    private final CustomizeRepository customizeRepository;
    private final CustomizeMapper customizeMapper;

    @Override
    public Map<String,Object> queryAll(CustomizeQueryCriteria criteria, Pageable pageable){
        Page<Customize> page = customizeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(customizeMapper::toDto));
    }

    @Override
    public List<CustomizeDto> queryAll(CustomizeQueryCriteria criteria){
        return customizeMapper.toDto(customizeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CustomizeDto findById(Long id) {
        Customize customize = customizeRepository.findById(id).orElseGet(Customize::new);
        ValidationUtil.isNull(customize.getId(),"Customize","id",id);
        return customizeMapper.toDto(customize);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomizeDto create(Customize resources) {
        //判断电话号码格式是否正确
        if(resources.getTelephone() != null){
            if(!resources.getTelephone().matches("^1[3456789]\\d{9}$")){
                throw new IllegalArgumentException("电话号码格式不正确");
            }
        }

        //判断邮箱格式是否正确
        if(resources.getEmail() != null){
            if(!resources.getEmail().matches("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$")){
                throw new IllegalArgumentException("邮箱格式不正确");
            }
        }
        resources.setStatus(CustomizeStatus.WAITING.getCode());
        //判断该用户电话号码是否已经使用
        if(resources.getTelephone() != null){
            Customize customize = customizeRepository.findByTelephoneAndStatus(resources.getTelephone(),CustomizeStatus.WAITING.getCode());
            if(customize != null){
                throw new IllegalArgumentException("已存在提交请求，无需重复提交");
            }
        }


        return customizeMapper.toDto(customizeRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Customize resources) {
        Customize customize = customizeRepository.findById(resources.getId()).orElseGet(Customize::new);
        ValidationUtil.isNull( customize.getId(),"Customize","id",resources.getId());
        customize.copy(resources);
        customizeRepository.save(customize);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            customizeRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CustomizeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CustomizeDto customize : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", customize.getName());
            map.put("电话号码", customize.getTelephone());
            map.put("邮箱", customize.getEmail());
            map.put("用途", customize.getContent());
            map.put("创建日期", customize.getCreateTime());
            map.put("更新时间", customize.getUpdateTime());
            map.put("创建者", customize.getCreateBy());
            map.put("更新者", customize.getUpdateBy());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}